package core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import stemmer.Stemmer;
import utility.file.TextFile;
import wordnet.IWordnetOperator;
import words.parser.QuestionParser;
import algorithm.winnow.TestWinnowCommittee;
import algorithm.winnow.TrainingWinnowCommittee;

public class Trainer {
	
	private Map<String,TrainingWinnowCommittee> _categoryToCommittee;
	private int _counter;
	public Trainer(){
		_categoryToCommittee = new HashMap<String,TrainingWinnowCommittee>();
		_counter = 0;
	}
	
	public void putQuestionUsing(String question, IWordnetOperator wordnet, Stemmer stemmer){
		QuestionParser parser = new QuestionParser(question);
		String cleanQuestion = parser.cleanQuestion();
		String category = parser.category();
		List<String> positiveCategories = new ArrayList<String>();
		
		boolean existCommitteeForCategory = false;
		
		for (String each : _categoryToCommittee.keySet()) {
			TrainingWinnowCommittee committee = _categoryToCommittee.get(each);
			boolean positiveExample = committee.category().equals(category);
			boolean correctPrediction = committee.trainWith(cleanQuestion, positiveExample);
			if(correctPrediction) positiveCategories.add(category);
			existCommitteeForCategory |= positiveExample;			
		}
		
		if(!existCommitteeForCategory) {
			TrainingWinnowCommittee committee = new TrainingWinnowCommittee(category,Main.TRAINING_WINNOW_COEFFICIENT, wordnet, stemmer);
			_categoryToCommittee.put(category, committee);
			committee.trainWith(cleanQuestion, true);
		}
		
		_counter++;
	}
	
	public Tester tester(){
		Tester tester = new Tester();
		for (String each : _categoryToCommittee.keySet()) {
			TrainingWinnowCommittee trainingCommittee = _categoryToCommittee.get(each);
			TestWinnowCommittee testCommittee = trainingCommittee.tester();
			tester.put(each,testCommittee);
		}
		return tester;
	}

	public void writeResultsOn(TextFile file) {
		for (String each : _categoryToCommittee.keySet()) {
			TrainingWinnowCommittee committee = _categoryToCommittee.get(each);
			committee.writeResultsForOn(_counter,each,file);
		}
	}

}
